use strict;
use warnings;
use Tk;
use YAML qw(LoadFile DumpFile);
use Coriander::Windows;
use Coriander::World;

system "cls";
# Set up the directory in which Coriander stores its configuration and world files.
if ($^O =~ /mswin/i) {
    use File::Basename 'dirname';
    $Coriander::appdir = dirname($0);
} else {
    $Coriander::appdir = $ENV{HOME} . "/.coriander";
    if (! -e $Coriander::appdir) {
        mkdir  $Coriander::appdir or die "Couldn't mkdir $Coriander::appdir: $!\n";
    }
}

# Set up a default configuration if there is no configuration file.   
if (not -e "$Coriander::appdir/coriander.yaml") {
    print "Creating default configuration file...\n";
    my %opts = (
        "ansi.fg_normal"    =>  "#bbbbbb",
        "ansi.bg_normal"    =>  "#000000",  
        "font.-family"      =>  "Fixedsys",
        "font.-size"        =>  11,
    );
    my $o = {};
    bless $o, "Coriander::World";
    $o->meta(file => "$Coriander::appdir/coriander.yaml");
    $o->flush(0);
    $o->set($_, $opts{$_}) for keys %opts;
    $o->save;
} 

# Load configuration.   
$Coriander::options = Coriander::World->load("../coriander.yaml");

# Let's go!
Coriander::Window::Main->new();
MainLoop;

# $setting = Coriander::localOrGlobal( $world, $key );
# Load a setting from a Coriander::World object, or fall back to the program-wide value
# for that setting if the world object doesn't have a value for the setting.
sub Coriander::localOrGlobal {
    my $world = shift;
    my $key = shift;
   
    my $value = undef;
    if (defined $world && $world->isa('Coriander::World')) {
        $value = return $world->get($key)
    }
    return $value // $Coriander::options->get($key);
}